package Core

import (
	"net/http"
	"strings"
	"path"
	"mime/multipart"
)

// declare HxRequest struct
type HxRequest struct {
	Raw *http.Request
	Param      []string
	method     string
	ip         string
	host       string
	remoteAddr string
	userAgent  string
	refer      string
	ext        string
	requestUrl string
}

// Get request method
func (this *HxRequest) Method() string {
	if this.method == "" {
		this.method = this.Raw.Method
	}
	return this.method
}

// Get remote ip
func (this *HxRequest) Ip() string {
	if this.ip == "" {
		this.ip = strings.Split(this.Raw.RemoteAddr, ":")[0]
	}
	return this.ip
}

// Get current domain
func (this *HxRequest) Domain() string {
	if this.host == "" {
		this.host = this.Raw.Host
	}
	return this.host
}

// Ger remote address
func (this *HxRequest) Remote() string {
	if this.remoteAddr == "" {
		this.remoteAddr = this.Raw.RemoteAddr
	}
	return this.remoteAddr
}

// Get request client user agent
func (this *HxRequest) UserAgent() string {
	if this.userAgent == "" {
		this.userAgent = this.Raw.UserAgent()
	}
	return this.userAgent
}

// Get refer location
func (this *HxRequest) Refer() string {
	if this.refer == "" {
		this.refer = this.Raw.Referer()
	}
	return this.refer
}

// Get is https request
func (this *HxRequest) IsHttps() bool {
	return this.Raw.TLS == nil
}

// Get request extension
func (this *HxRequest) Ext() string {
	if this.ext == "" {
		this.ext = path.Ext(this.Raw.URL.Path)
	}
	return this.ext
}

// Get request uri, with query string and fragment
func (this *HxRequest) RequestURI() string {
	if this.requestUrl == "" {
		this.requestUrl = this.Raw.RequestURI
	}
	return this.requestUrl
}

// Get base uri
func (this *HxRequest) BaseURL() string {
	if this.IsHttps() {
		return "https://" + this.Domain()
	}
	return "http://" + this.Domain()
}

// Get request header
func (this *HxRequest) Header(key string) string {
	return this.Raw.Header.Get(key)
}

// Get request cookie value
func (this *HxRequest) Cookie(name string) string {
	c, e := this.Raw.Cookie(name)
	if e != nil {
		return ""
	}
	return c.Value
}

// Check isAjax request
func (this *HxRequest) IsAjax() bool {
	return this.Header("X-Requested-With") == "XMLHttpRequest"
}

// Get uploaded file by key string
func (this *HxRequest) File(key string) (multipart.File, *multipart.FileHeader, error) {
	this.Raw.ParseMultipartForm(32<<20)
	return this.Raw.FormFile(key)
}

// Create new HxRequest struct
func Request(r *http.Request) *HxRequest {
	req := &HxRequest{}
	req.Raw = r
	req.Param = strings.Split(r.URL.Path, "/")
	return req
}

